﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfScratchApp.UserControls
{
    /// <summary>
    /// Interaction logic for ByteControl.xaml
    /// </summary>
    public partial class ByteControl : UserControl
    {
        //private Dictionary<int, CheckBox> _controlElements = new Dictionary<int, CheckBox>(); 

        public ByteControl()
        {
            InitializeComponent();

            UpdateDisplay();
            
        }

        public static readonly DependencyProperty ValueProperty = 
            DependencyProperty.Register("Value", typeof (byte), typeof (ByteControl), new PropertyMetadata(default(byte), DependencyPropertyChanged));

        private static void DependencyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ByteControl)d).UpdateDisplay();
        }

        public byte Value
        {
            get
            {
                return (byte) GetValue(ValueProperty);
            }
            set
            {
                SetValue(ValueProperty, value);
                UpdateDisplay();
            }
        }

        private void UpdateDisplay()
        {
            var value = Value;
            foreach (var uiElement in ctlContainer.Children)
            {
                var controlElement = uiElement as CheckBox;
                if (controlElement != null)
                {
                    var index = Convert.ToInt32(controlElement.Tag);
                    controlElement.IsChecked = (value & Convert.ToByte(Math.Pow(2, index))) > 0;
                }
            }
        }

        private void chkBit_Click(object sender, RoutedEventArgs e)
        {
            UpdateValue();
        }

        private void UpdateValue()
        {
            byte value = 0; 
            foreach (var uiElement in ctlContainer.Children)
            {
                var controlElement = uiElement as CheckBox;
                if (controlElement != null)
                {
                    var index = Convert.ToInt32(controlElement.Tag);
                    if (controlElement.IsChecked == true)
                    {
                        value += Convert.ToByte(Math.Pow(2, index));
                    }
                }
            }
            Value = value;
        }
    }
}
